package com.example.wxsmart.resources;

import cn.hutool.core.util.ObjectUtil;
import com.example.wxsmart.pojo.Question;
import com.example.wxsmart.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Luojunxian
 * @data 2022/5/31 11:29
 * @classname RabbitMqListenerResources
 */
@Slf4j
@Component
public class RabbitMqListenerResources {
    public static final String EXCHANGE_NAME = "ES_EXCHANGE";
    public static final String QUEUE_NAME = "ES_QUEUE";
    public static final String ROUTING_KEY = "ES_ROUTING_KEY";

    public int count = 0;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private QuestionService questionService;

    @Resource
    private ElasticSearchDocumentResources documentResources;

    /**
     * rabbitmq:监听消息
     *
     * @param idList id列表
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = EXCHANGE_NAME),
            value = @Queue(QUEUE_NAME),
            key = ROUTING_KEY))
    public void listenerMessage(List<Integer> idList) {
        log.info("RabbitMqListener:消息监听成功,idList={}", idList);
        List<Question> questionList = questionService.getQuestionList(idList);

        try {
            // 删除
            if (ObjectUtil.isNotEmpty(idList)) {
                documentResources.deleteDocument(idList);
                log.info("RabbitMqListener:消息操作为delete");
                return;
            }

            // 添加/修改
            documentResources.batchDocument(questionList);
            log.info("RabbitMqListener:消息操作为add/update");
        } catch (Exception e) {
            try {
                if (count == 3){
                    count = 0;
                    return;
                }
                log.error("ElasticSearch:同步失败,5秒后重新发送消息再次同步...");
                log.error("ElasticSearch:失败原因:{}", e.getMessage());
                Thread.sleep(5000);
                count++;
                sendMessage(idList);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * rabbitmq:发送消息
     *
     * @param idList id列表
     */
    public void sendMessage(List<Integer> idList) {
        rabbitTemplate.convertAndSend(RabbitMqListenerResources.EXCHANGE_NAME,
                RabbitMqListenerResources.ROUTING_KEY, idList);

        log.info("RabbitMq:消息发送成功,message:{}", idList);
    }

}
